<?php
namespace Home\Controller;
//require 'vendor/autoload.php';
use think\Controller;
use Think\Upload;
use JPush\Client;
use JPush\Exceptions\APIConnectionException;
use JPush\Exceptions\APIRequestException;
use Think\Model;
class IndexController extends Controller
{

    protected function _initialize()
    {
        exit;
    }
    /*进入主页面*/
    public function index()
    {
        if (isset($_SESSION["msg"]['id'])) {
            $id=$_SESSION["msg"]['id'];
            $month=date('Y-m');

            //$money = $this->get_month_money($id,$month);

            $beginThismonth=date('Y-m-d H:i:s',mktime(0,0,0,date('m'),1,date('Y')));//获取本月开始时间戳

            $nowtime = date('Y-m-d H:i:s',mktime());//获取当前的时间戳
            //php获取昨日起始时间戳和结束时间戳

            //$beginYesterday=date('Y-m-d H:i:s',mktime(0,0,0,date('m'),date('d')-1,date('Y')));

            //$endYesterday=date('Y-m-d H:i:s',mktime(0,0,0,date('m'),date('d'),date('Y'))-1);

            $date=date('Y-m-d');
            $endYesterday = date($date. ' 12:00:01');
            $beginYesterday=date('Y-m-d',strtotime("$endYesterday -1 days"))." 12:00:00";
            echo $beginYesterday."<br/>";
            echo $endYesterday."<br/>";

            $pcommission = $this->get_day_pmoney($id,$beginYesterday,$endYesterday);
            $p_money = $this->get_month_pmoney($id,$beginThismonth,$nowtime);

            $commission = $this->get_day_money($id,$beginYesterday,$endYesterday);//获取昨日工资奖金
            //var_dump($commission);die;
            $money = $this->get_month_money($id,$beginThismonth,$nowtime);//获取月工资奖金
            //var_dump($money);die;

            $counts = M("register")->where("agent_id=$id or upper_agent_id=$id or upper_upper_agent_id=$id")->count();
            $today=date('Y-m-d 00:00:00');
            $yestoday=date('Y-m-d 00:00:00',strtotime("-1 day"));
            $map['create_time'] = array(array('EGT', $yestoday), array('ELT', $today));
            $data['create_time'] = array(array('EGT', $yestoday), array('ELT', $today));
            //昨天下级注册人数
            $count = M("register")->where("agent_id=$id or upper_agent_id=$id or upper_upper_agent_id=$id")->where($map)->count();

            $res=M("register")->where('id='.$id)->find();

            if ($res) {
                //$commission=$res['commission'];
                $commissions=$res['commissions'];
                $register_name=$res['register_name'];
            }
            $this->assign("commission",$commission);
            $this->assign("commissions",$commissions);
            $this->assign("register_name",$register_name);
            $this->assign("count",$count);
            $this->assign("money",$money);
            $this->assign("p_money",$p_money);
            $this->assign("pcommission",$pcommission);
            $this->assign("counts",$counts);  
        }

        $this->display("index");
        
        
    }
    //获取昨天的公资奖金
    function get_day_money($id,$beginYesterday,$endYesterday){
        $data['time'] = array('between',array($beginYesterday,$endYesterday));
        $commission = M("bonus")->where('uid='.$id)->where($data)->sum('money');
        return $commission;
    }

    //获取昨天的充值奖金
    function get_day_pmoney($id,$beginYesterday,$endYesterday){
        $data['ctime'] = array('between',array($beginYesterday,$endYesterday));
        $p_money = M("pbonus")->where('uid='.$id)->where($data)->sum('moneys');
        return $p_money;
    }

    //月充值奖金统计
    function get_month_pmoney($id,$beginThismonth,$nowtime){
        $data['ctime'] = array('between',array($beginThismonth,$nowtime));
        $p_money = M("pbonus")->where('uid='.$id)->where($data)->sum('moneys');
        return $p_money;
    }
    //本月到现在的工资奖金
    function get_month_money($id,$beginThismonth,$nowtime){
        $data['time'] = array('between',array($beginThismonth,$nowtime));
        $money = M("bonus")->where('uid='.$id)->where($data)->sum('money');
        return $money;
    }

    //月工资奖金统计
//    function get_month_money($id,$month){
//        $data['time']=array('like',"$month%");
//        $team1=M("bonus")->join('register on bonus.mid=register.id')->where('uid='.$id.' and remark=1')->where($data)->select();
//
//        $team2=M("bonus")->join('register on bonus.mid=register.id')->where('uid='.$id.' and remark=2')->where($data)->select();
//
//        $team3=M("bonus")->join('register on bonus.mid=register.id')->where('uid='.$id.' and remark=3')->where($data)->select();
//
//        $money1 = 0;
//        foreach ($team1 as $key=> $value) {
//            $money1 += $value['money'];
//        }
//        $money2 = 0;
//        foreach ($team2 as $key=> $value) {
//            $money2 += $value['money'];
//        }
//        $money3 = 0;
//        foreach ($team3 as $key=> $value) {
//            $money3 += $value['money'];
//        }
//
//        $money=$money1+$money2+$money3;
//        return $money;
//    }

    function xieyi(){
        $this->display();
    }

    public function grant()
    {

        // 开启事务
        M()->startTrans();

        try
        {
            // 第一步：导入员工工资
            $this->importAchievement();

            // 第二步：根据导入的工资进行结算奖金
            $this->settleAchievement();

            // 提交事务
            M()->commit();
        }
        catch (Exception $exception)
        {
            // 回滚操作
            M()->rollback();
        }
    }


    private function importAchievement()
    {
        // 打开工资记录文件
        $file = fopen('C:\INSERT.log', 'r');

        $number = $this->getLastSeek();

        // 根据上次读取的位置，对文件进行定位
        fseek($file, $number);

        // 存储SQL语句
        $sqlArray = [];

        // 输出文本中所有的行，直到文件结束为止。
        while(! feof($file))
        {
            // 逐行读取数据
            $line = trim(fgets($file));

            // 如果为空行，则不做任何处理
            if (empty($line))
            {
                continue;
            }

            // 逐行读取SQL语句
            $sqlArray[]= $line;

            // SQL语句每次最多执行500条
            if (count($sqlArray) >= 500)
            {
                // 执行SQL语句
                (new Model())->execute(join('', $sqlArray));

                // 清空存储的语句
                $sqlArray = [];
            }

        }

        //var_dump(join('', $sqlArray));
        if (!empty($sqlArray))
        {
            (new Model())->execute(join('', $sqlArray));
            // 清空存储的语句
            $sqlArray = [];
        }

        $x = ftell($file);
        // 存储当前读取到的位置
        $this->setLastSeek($x);

        // 关闭文件
        fclose($file);
    }

    // 上次读取的位置
    private function getLastSeek()
    {
        // 记录文件
        $file = DATA_PATH . 'achievement.txt';

        // 获取文件内容
        $seek = file_get_contents($file);

        // 返回上次读取的位置
        return empty($seek) ? 0 : intval($seek);
    }

    // 更新上次读取的位置
    private function setLastSeek($seek)
    {
        // 记录文件
        $file = DATA_PATH . 'achievement.txt';

        // 设置文件内容
        file_put_contents($file, $seek);
    }


    // 通过工资进行发放
    private function grantByAchievement($achievement, $params)
    {

        // 获取员工数据
        $userinfo = M('register')
            ->where([
                'bind_id' => $achievement['jsmc'],
                'bind_did' => $achievement['jg_dm']
            ])
            ->find();
        if($userinfo){
            if($userinfo['agent_id']>0){
                //奖金发放
                $agent = send_commission($userinfo['id'],$userinfo['agent_id'],$params['rate_1'],1,$achievement);//给推荐人上级发放奖金
                if($agent){
                    if($userinfo['upper_agent_id']>0){
                        $grandpa = send_commission($userinfo['id'],$userinfo['upper_agent_id'],$params['rate_2'],2,$achievement);//给推荐人上上级发放奖金
                        if($grandpa){
                            if($userinfo['upper_upper_agent_id']>0){
                                $greatpa = send_commission($userinfo['id'],$userinfo['upper_upper_agent_id'],$params['rate_3'],3,$achievement);//给推荐人上上上级发放奖金
                                if($greatpa){
                                    $this->send_push($userinfo['agent_id'],$userinfo['agent_tel'],$params['rate_1']);
                                    $this->send_push($userinfo['upper_agent_id'],$userinfo['upper_agent_tel'],$params['rate_2']);
                                    $this->send_push($userinfo['upper_upper_agent_id'],$userinfo['upper_upper_agent_tel'],$params['rate_3']);
                                }
                            }else{
                                $this->send_push($userinfo['agent_id'],$userinfo['agent_tel'],$params['rate_1']);
                                $this->send_push($userinfo['upper_agent_id'],$userinfo['upper_agent_tel'],$params['rate_2']);
                            }
                        }
                    }else{
                        $this->send_push($userinfo['agent_id'],$userinfo['agent_tel'],$params['rate_1']);
                    }
                }
            }
        }

    }



    public function send_push($uid,$tel,$commission){

        $client = new Client(C('JPUSH.APP_KEY'), C('JPUSH.MASTER_SECRET'));

        try {
            $client->push()
                ->setPlatform('android')
                ->addAlias($tel)
                ->androidNotification('紫薇阁温馨提示：您获得奖金'.$commission.'元', [
                    'extras' => [
                        'type' => '/index.php/home/index/commission/id/' . $uid
                    ]
                ])
                ->options(array(
                    'apns_production' => false,
                ))
                ->send();
        } catch (APIConnectionException $e) {
            // try something here
            //print $e;
        } catch (APIRequestException $e) {
            // try something here
            //print $e;
        }

    }

    // 结算工资
    private function settleAchievement()
    {

        // 结算日期
        $date = strtotime(I('date')) > 0 ? date('Y-m-d', strtotime(I('date'))) : date('Y-m-d');
        // 开始时间
        $startTime = date('Y-m-d 12:00:00', strtotime('-1 day', strtotime($date)));
        //print_r($startTime);
        // 结束时间
        $endTime = $date . ' 12:00:00';
        //print_r($endTime);die;
        // 奖金参数
        $ratio = M('ratio')->find();
        $params = [
            'rate_1' => floatval($ratio['agent_ratio']),
            'rate_2' => floatval($ratio['upper_agent_ratio']),
            'rate_3' => floatval($ratio['upper_upper_agent_ratio'])
        ];

        // 获取所有需要结算的工资
        do
        {
            // 获取满足条件的数据
            $list = M('achievement', 'ims_')
                ->where([
                    'status' => 0,
                    'createtime' => ['between', [$startTime, $endTime]]
                ])
                ->limit(100)
                ->select();
            // 遍历数据发放奖金
            foreach ($list as $item)
            {
                // 发放奖金
                $this->grantByAchievement($item, $params);

                // 更新状态
                M('achievement', 'ims_')->where(['hid'=>$item['hid']])->save(['status'=>1]);
            }
        }
        while($list);
    }


    //文件的读取拷贝
    /*public function kaobei(){
        $file="C://INSERT.log";
        $newfile="C://INSERT1.log";
        if (file_exists($file) == false){
           die ('文件不在,无法复制');
        }
        $result = copy($file, $newfile);
        $myfile = fopen($newfile, "r") or die("Unable to open file!");
        $user=array();
        $i=0;
        while(!feof($myfile)) {
          $user[$i]=fgets($myfile);
          $i++;
        }
        fclose($myfile);
        return $user;
    }*/
    //读取文件
    /*public function file(){
        $model=D("ImsAchievement");
        $count=$model->count();
 
        $model->where('1')->delete();
        M('register')->where('id > 0')->save(array('commission'=>0));
        $user=$this->kaobei();
        $users=join("",$user);
        $res=D("ImsAchievement")->execute($users);
        //var_dump($res);die;
        //获取奖金比例
        $ratio= M('ratio')->find();
        //一级分销奖金比例
        $ratio1=floatval($ratio['agent_ratio']);
        //二级分销奖金比例
        $ratio2=floatval($ratio['upper_agent_ratio']);
        //三级分销奖金比例
        $ratio3=floatval($ratio['upper_upper_agent_ratio']);
        //var_dump($ratio1);die;
        if ($res) {
            $now=date('Y-m-d H:i:s',time());
            $time=date('Y-m-d 12:00:00');
            //var_dump($now);
            //var_dump($time);die;
            if ($now>=$time) {
                $today=date('Y-m-d 11:59:59');
                $yestoday=date('Y-m-d 12:00:01',strtotime("-1 day"));

                $map['createtime'] = array(array('EGT', $yestoday), array('ELT', $today));
                //var_dump($map['createtime']);die;
            } else {
                //echo 123;die;
                $today=date('Y-m-d 11:59:59',strtotime("-1 day"));
                $yestoday=date('Y-m-d 12:00:01',strtotime("-2 day"));
                $map['createtime'] = array(array('EGT', $yestoday), array('ELT', $today));
            }

            $ress=D("ImsAchievement")->join('register on register.bind_id=ims_achievement.jsmc and register.bind_did=ims_achievement.jg_dm')->field('hid,id,jg_dm,tel,createtime,TCJE as money')->where('status = 0')->where($map)->select();
            //$ress=D("ImsAchievement")->join('register on register.bind_id=ims_achievement.jsmc and register.bind_did=ims_achievement.jg_dm')->field('hid,id,jg_dm,tel,createtime,TCJE as money')->where('status = 0')->select();
            //var_dump($ress);die;
            foreach ($ress as $key => $value) {
                $id=$value['id'];
                //$TCJE=$value['TCJE'];
                //echo $TCJE."<br/>";
                $hid=$value['hid'];
                $jg_dm=$value['jg_dm'];
                $number=$value['money']*10/100;
                $tel=$value['tel'];
                //echo $id."--".$uid."--".$jg_dm."--".$number."<br/>";
                $time=$value['createtime'];
                $agent=M('register')->where('id='.$id)->find();
                $agent_id=$agent['agent_id'];//上级id
                $upper_agent_id=$agent['upper_agent_id'];//上上级id
                $upper_upper_agent_id=$agent['upper_upper_agent_id'];//上上级id
                $agent_lock=$agent['lock'];//上级是否锁定
                if($agent_id!=0){//该用户为顶层并且没有上级       
                    $upper_agent=M('register')->where('id='.$agent_id)->find();
                    $upper_agent_lock=$upper_agent['lock'];//上上级是否锁定
                    if($upper_agent_id!=0){
                        $upper_upper_agent=M('register')->where('id='.$upper_agent_id)->find();
                        $upper_upper_agent_lock=$upper_upper_agent['lock'];//上上上级是否锁定
                        if ($upper_upper_agent_id!=0) {
                            if($upper_upper_agent_lock!=0&&$upper_agent_lock!=0&&$agent_lock!=0){
                                $commission1=$number*$ratio1;
                                $commission2=$number*$ratio2;
                                $commission3=$number*$ratio3;
                                //工资流入奖金池的数量
                                $jiang=$number-$commission1-$commission2-$commission3;
                            }elseif($upper_upper_agent_lock==0&&$upper_agent_lock!=0&&$agent_lock!=0){
                                $commission1=$number*$ratio1;
                                $commission2=$number*$ratio2;
                                $jiang=$number-$commission1-$commission2;
                            }elseif($upper_upper_agent_lock!=0&&$upper_agent_lock==0&&$agent_lock!=0){
                                $commission1=$number*$ratio1;
                                $commission3=$number*$ratio3;
                                //工资流入奖金池的数量
                                $jiang=$number-$commission1-$commission3;
                            }elseif($upper_upper_agent_lock!=0&&$upper_agent_lock!=0&&$agent_lock==0){
                                $commission2=$number*$ratio2;
                                $commission3=$number*$ratio3;
                                //该用户工资昨日流入奖金池的数量
                                $jiang=$number-$commission2-$commission3;
                            }elseif ($upper_upper_agent_lock==0&&$upper_agent_lock==0&&$agent_lock==0) {
                                $jiang=$number;
                            }
                            if($commission3){
                                //把上上上级所得奖金写入数据库
                                M('register')->where('id='.$upper_upper_agent_id)->setInc('commissions',$commission3);
                                M('register')->where('id='.$upper_upper_agent_id)->setInc('commission',$commission3);

                                $dat['mid']=$id;
                                $dat['tel']=$tel;
                                $dat['time']=$dat['time']=$time;
                                $dat['TCJE']=$value['money'];
                                $dat['stime']=date('Y-m-d H:i:s',time());
                                $dat['uid']=$upper_upper_agent_id;
                                $dat['money']=$commission3;
                                $dat['remark']=3;
                                M('bonus')->add($dat);
                            }
                            if($commission2){
                                //把上上级所得奖金写入数据库
                                M('register')->where('id='.$upper_agent_id)->setInc('commissions',$commission2);
                                M('register')->where('id='.$upper_agent_id)->setInc('commission',$commission2); 

                                $dat['mid']=$id;
                                $dat['tel']=$tel;
                                $dat['time']=$dat['time']=$time;
                                $dat['TCJE']=$value['money'];
                                $dat['stime']=date('Y-m-d H:i:s',time());
                                $dat['uid']=$upper_agent_id;
                                $dat['money']=$commission2;
                                $dat['remark']=2;
                                M('bonus')->add($dat);
                            }
                            if($commission1){
                                //把上级所得奖金写入数据库
                                M('register')->where('id='.$agent_id)->setInc('commissions',$commission1);
                                M('register')->where('id='.$agent_id)->setInc('commission',$commission1);

                                $dat['mid']=$id;
                                $dat['tel']=$tel;
                                $dat['time']=$time;
                                $dat['TCJE']=$value['money'];
                                $dat['stime']=date('Y-m-d H:i:s',time());
                                $dat['uid']=$agent_id;
                                $dat['money']=$commission1;
                                $dat['remark']=1;
                                M('bonus')->add($dat);
                            }
                              
                        }else{
                            if ($upper_agent_lock!=0&&$agent_lock!=0) {

                                $commission1=$number*$ratio1;

                                $commission2=$number*($ratio2+$ratio3);

                                $jiang=$number-$commission1-$commission2;
                            } elseif($upper_agent_lock!=0&&$agent_lock==0) {

                                $commission2=$number*($ratio2+$ratio3);

                                $jiang=$number-$commission2;
                            }elseif($upper_agent_lock==0&&$agent_lock!=0){

                                $commission1=$number*$ratio1;
                                //该用户工资昨日流入奖金池的数量
                                $jiang=$number-$commission1;
                            }elseif ($upper_agent_lock==0&&$agent_lock==0) {
                                //该用户工资昨日流入奖金池的数量
                                $jiang=$number;
                            }
                            if ($commission2) {
                                //把上上级所得奖金写入数据库
                                M('register')->where('id='.$upper_agent_id)->setInc('commissions',$commission2);
                                M('register')->where('id='.$upper_agent_id)->setInc('commission',$commission2);
                                //var_dump(M('register')->getLastSql());
                                $dat['mid']=$id;
                                $dat['tel']=$tel;
                                $dat['time']=$time;
                                $dat['TCJE']=$value['money'];
                                $dat['stime']=date('Y-m-d H:i:s',time());
                                $dat['uid']=$upper_agent_id;
                                $dat['money']=$commission2;
                                $dat['remark']=2;
                                M('bonus')->add($dat);
                            }
                            if ($commission1) {
                                //把上级所得奖金写入数据库
                                M('register')->where('id='.$agent_id)->setInc('commissions',$commission1);
                                M('register')->where('id='.$agent_id)->setInc('commission',$commission1);
                                //var_dump(M('register')->getLastSql());
                                $dat['mid']=$id;
                                $dat['tel']=$tel;
                                $dat['time']=$time;
                                $dat['TCJE']=$value['money'];
                                $dat['stime']=date('Y-m-d H:i:s',time());
                                $dat['uid']=$agent_id;
                                $dat['money']=$commission1;
                                $dat['remark']=1;
                                M('bonus')->add($dat);
                            }
                        }
                    }else{
                        if ($agent_lock!=0) {
                            $commission1=$number*($ratio1+$ratio2+$ratio3);
                            //该用户工资昨日流入奖金池的数量
                            $jiang=$number-$commission1;
                        } elseif($agent_lock==0) {
                            //该用户工资昨日流入奖金池的数量
                            $jiang=$number;
                        }
                        if($commission1){
                            //把上级所得奖金写入数据库
                            M('register')->where('id='.$agent_id)->setInc('commissions',$commission1);
                            M('register')->where('id='.$agent_id)->setInc('commission',$commission1);
                            $dat['mid']=$id;
                            $dat['tel']=$tel;
                            $dat['time']=$time;
                            $dat['TCJE']=$value['money'];
                            $dat['stime']=date('Y-m-d H:i:s',time());
                            $dat['uid']=$agent_id;
                            $dat['money']=$commission1;
                            $dat['remark']=1;
                            M('bonus')->add($dat);
                        }

                    }

                //把奖金数目写进奖金池
                $data['uid']=$id;
                $data['tel']=$tel;
                $data['time']=date('Y-m-d H:i:s',time());
                $data['money']=$jiang;
                M('commission')->add($data);
                }
                $da['status']=1;
                D('ImsAchievement')->where('hid='.$hid)->save($da); 
            }    
            $this->tongji();
        }
    }*/

    /*function tongji(){
        $now=date('Y-m-d H:i:s',time());
        $time=date('Y-m-d 12:00:00');

        if ($now>=$time) {
            $today=date('Y-m-d 11:59:59');
            $yestoday=date('Y-m-d 12:00:01',strtotime("-1 day"));

            $map['createtime'] = array(array('EGT', $yestoday), array('ELT', $today));
        } else {
            $today=date('Y-m-d 11:59:59',strtotime("-1 day"));
            $yestoday=date('Y-m-d 12:00:01',strtotime("-2 day"));
            $map['createtime'] = array(array('EGT', $yestoday), array('ELT', $today));
        }

        $map['createtime'] = array(array('EGT', $yestoday), array('ELT', $today));
        $ress=D("ImsAchievement")->join('register')->where($map)->field('id,tel,commission')->group('id')->select();
        foreach ($ress as $key => $value) {
            $id=$value['id'];
            $data['tel']=$value['tel'];
            $data['uid']=$id;
            $data['time']=$now;
            $data['money']=$value['commission'];
            M('reward')->add($data);

            $res=M('register')->where('id='.$id)->find();
            if ($res) {
                $tel=$res['tel'];
                $num=$res['num'];
                $commission=$res['commission'];
            }
            $this->client($id,$tel,$num,$commission);

        }

    }*/


    /*手机号验证*/
    Public function change()
    {
        //获得ajax提交的数据
        $mobile = $_POST["mobile"];
        if ($mobile != null) {
            $result = M("register")->where("tel={$mobile}")->find();
            if ($result) {
                echo "1";
            }
        }
    }

    Public function change1()
    {
        //获得ajax提交的数据
        $mobile = $_POST["txt_Mobile1"];
        if ($mobile != null) {
            //$result = M("register")->where("tel={$mobile}")->find();
            $param["agent_tel"] = $mobile;//邀请人手机号(上一级手机号)
            $agent_id=M("register")->where("tel=".$param["agent_tel"])->find();
            if (!$agent_id) {
                echo "3";
            }
        }
    }

    /*验证码*/
    public function verify()
    {

        $mobile = $_POST["mobile"];

        //生成随机验证码
        $code = "";
        $n = 6;
        for ($i = 1; $i <= $n; $i++) {
            $code .= rand(0, 9);
        }
        $time = time();
        $arr = array("mobile" => $mobile, "verify" => $code, "time" => $time);
        //dump($arr['verify']);die;
        $_SESSION["verify"] = $arr;

        echo json_encode($_SESSION['verify']['verify']);
        
        code($mobile, $code);
    }

    //注册
    public function register()
    {
        $id=I("id");
        //var_dump($id);die;
        if($id)
        {
            $mobile = M("register")->where("id={$id}")->find();

            $this->assign("tel",$mobile);
            $this->assign("agent_id",$id);
        }
        $this->display();
    }

    public function reg()
    {
        if ($_POST) {
            $param["agent_tel"] = I("txt_Mobile");//邀请人手机号(上一级手机号)
            if($param["agent_tel"]=="")
            {
                $param["agent_id"]=0;//上一级id
                $param['upper_agent_id'] = 0;//上上一级id
                $param['upper_upper_agent_id'] = 0;//上上一级id
                $param['upper_agent_tel'] = 0;//上上一级手机号
                $param['upper_upper_agent_tel'] = 0;//上上上一级手机号
            }else
            {   
                $param["agent_tel"] = I("txt_Mobile");//邀请人手机号(上一级手机号)
                $agent=M("register")->where("tel=".$param["agent_tel"])->find();//上一级用户信息
                if($agent){
                    $agent_id = $agent['id'];//上一级id
                    $upper_agent_id = $agent['agent_id'];//上上级id
                    $upper_upper_agent_id = $agent['upper_agent_id'];//上上上级id
                    $agent_tel = $agent['tel'];//上一级id
                    $upper_agent_tel = $agent['agent_tel'];//上上级id
                    $upper_upper_agent_tel = $agent['upper_agent_tel'];//上上上级id
                    if($upper_upper_agent_id>0){
                        $param['upper_upper_agent_id']=$upper_upper_agent_id;
                        $param['upper_agent_id']=$upper_agent_id;
                        $param['agent_id']=$agent_id;
                        $param['upper_upper_agent_tel']=$upper_upper_agent_tel;
                        $param['upper_agent_tel']=$upper_agent_tel;
                        $param['agent_tel']=$agent_tel;
                    }else{
                        if($upper_agent_id>0){
                            $param['upper_upper_agent_id']=0;
                            $param['upper_agent_id']=$upper_agent_id;
                            $param['agent_id']=$agent_id;
                            $param['upper_upper_agent_tel']=0;
                            $param['upper_agent_tel']=$upper_agent_tel;
                            $param['agent_tel']=$agent_tel;
                        }else{
                            $param['upper_upper_agent_id']=0;
                            $param['upper_agent_id']=0;
                            $param['agent_id']=$agent_id;
                            $param['upper_upper_agent_tel']=0;
                            $param['upper_agent_tel']=0;
                            $param['agent_tel']=$agent_tel;
                        }
                    }
                }else{
                    $this->error('推荐人手机号填写有误');
                }
                       
            }
            $param["register_name"] = I("register_name");//用户名
            $param["tel"] = I("txt_UserName");//手机号
            $param["password"] = I("txt_Pwd");//密码
            $param["passwordTwo"] = I("txt_PwdTwo");//确认密码
            $param["verify"] = I("txt_UserName2");//验证码
            //dump($param["verify"]);die;
            $param["agent_tel"] = I("txt_Mobile");//邀请人手机号(上一级手机号)
            if ($param["register_name"] == "") {
                $this->error("用户名不能为空！");
            } 
           if ($param["tel"] == "") {
                $this->error("手机号不能为空！");
            } 
            if (!preg_match("/^1[34578]{1}\d{9}$/", $param["tel"])) {
                $this->error("请输入合法的手机号！");
            } 
            if (preg_match("/^1[34578]{1}\d{9}$/", $param["tel"])) {
                $result = M("register")->where("tel={$param["tel"]}")->find();
                //验证
                if ($result) {
                    $this->error("该手机号已注册过，请换一个手机号");
                }
            } 
            if (strlen($param["password"]) < 6 || strlen($param["password"]) > 16) {
                    $this->error("请输入6-16字符！");
            } 
            if ($param["passwordTwo"] !== $param["password"]) {
                    $this->error("两次密码不一致！");
            }
            $param['password']=md5($param["password"]);
            $data = M("register");
            $re = $data->data($param)->add();
            if ($re) {
                $this->redirect("/index.php/home/login/login");
            } else {
                $this->redirect("/index.php/home/index/register");
            }
        } else {
            $this->display("register");
        }
    }
    //贷款申请身份证验证
    Public function check()
    {
        //获得ajax提交的数据
        $param["agent_tel"] = $_POST("mobile1");//邀请人手机号(上一级手机号)
        //var_dump($param['agent_tel']);die;
        $agent_id=M("register")->where("tel=".$param["agent_tel"])->find();
        if(!$agent_id){
            echo 2;
        }
    }

    /*申请贷款第一步验证码*/
    // public function code()
    // {
    //     $tel = $_POST["tel"];

    //     //生成随机验证码
    //     $code = "";
    //     $n = 6;
    //     for ($i = 1; $i <= $n; $i++) {
    //         $code .= rand(0, 9);
    //     }
    //     $time = time();
    //     $arr = array("mobile" => $tel, "verify" => $code, "time" => $time);
    //     $_SESSION["code"] = $arr;
    //     code($tel, $code);
    // }

    /*申请贷款第二步*/
    public function applyloan()
    {

        $id = $_GET['id'];
        $loan_name = $_GET['loan_name'];
        $this->assign("loan_name", $loan_name);
        $this->assign("id", $id);
        $this->display("applyloan");


    }

    public function applysubmit()
    {
        if (IS_POST) {

           if (($_SESSION["code"]["time"] + 120) < time()) {
                unset($_SESSION["code"]);
                $this->error("验证码已过期，请重新获得！");
            }
            $param['register_id']=$_GET['id'];
            $agent = M("register")->where("id={$param['register_id']}")->find();
            if($agent['agent_id']==0)
            {
                $param['agent_name']=0;
            }else
            {
                $agent_name=M("register")->where("id={$agent['agent_id']}")->find();
                $param['agent_name']=$agent_name['register_name'];
            }
            $param['name'] = $_POST['borrower'];
            $param['loan_name'] = $_GET['loan_name'];
            $param['borrow_money'] = $_POST['number'];
            $param['tel'] = $_POST['tel'];
            $code = $_POST['code'];
            $param['city'] = $_POST['cities'];


            $param['id_number'] = I('id_number');
            $param['salary'] = I('salary');
            $param['apply_limit'] = $_POST['limit'];


            $param['is_fund'] = $_POST['fund'];

            $param['is_sec'] = $_POST['sec'];

            $param['area'] = I('area');
            $param['type'] = $_POST['type'];


            $param['is_car'] = $_POST['car'];

            $param['credit'] = $_POST['credit'];


            if($code=="")
            {
                $this->error("验证码不能为空！");
            }else if($code!==$_SESSION['code']['verify'])
            {
                $this->error("验证码不一致！");
            }

            $data = M("loanborrower");
            $result = $data->data($param)->add();
            if ($result) {
                $this->redirect("index/index");
            } else {
                $this->redirect("index/applyloan1");
            }


        } else {
            $this->display("applyloan");
        }
    }

    public function client($id,$tel,$num,$commission){
        
        $client = new JPushClient(C('JPUSH.APP_KEY'), C('JPUSH.MASTER_SECRET'));
        
        try {
            $response = $client->push()
                ->setPlatform('android')
                // 一般情况下，关于 audience 的设置只需要调用 addAlias、addTag、addTagAnd  或 addRegistrationId
                // 这四个方法中的某一个即可，这里仅作为示例，当然全部调用也可以，多项 audience 调用表示其结果的交集
                // 即是说一般情况下，下面三个方法和没有列出的 addTagAnd 一共四个，只适用一个便可满足大多数的场景需求

                ->addAlias($tel)
                  ->androidNotification('紫薇阁温馨提示：您昨天所得奖金'.$commission.'元', [
                       'extras' => [
                         'type' => '/index.php/home/index/commission/id/'.$id
                       ]
                     ])
                
                ->options(array(
                    // sendno: 表示推送序号，纯粹用来作为 API 调用标识，
                    // API 返回时被原样返回，以方便 API 调用方匹配请求与返回
                    // 这里设置为 100 仅作为示例

                    // 'sendno' => 100,

                    // time_to_live: 表示离线消息保留时长(秒)，
                    // 推送当前用户不在线时，为该用户保留多长时间的离线消息，以便其上线时再次推送。
                    // 默认 86400 （1 天），最长 10 天。设置为 0 表示不保留离线消息，只有推送当前在线的用户可以收到
                    // 这里设置为 1 仅作为示例

                    // 'time_to_live' => 1,

                    // apns_production: 表示APNs是否生产环境，
                    // True 表示推送生产环境，False 表示要推送开发环境；如果不指定则默认为推送生产环境

                    'apns_production' => false,

                    // big_push_duration: 表示定速推送时长(分钟)，又名缓慢推送，把原本尽可能快的推送速度，降低下来，
                    // 给定的 n 分钟内，均匀地向这次推送的目标用户推送。最大值为1400.未设置则不是定速推送
                    // 这里设置为 1 仅作为示例

                    // 'big_push_duration' => 1
                ))
                ->send();
                //print_r($response);


        } catch (\JPush\Exceptions\APIConnectionException $e) {
            // try something here
            //print $e;
        } catch (\JPush\Exceptions\APIRequestException $e) {
            // try something here
            //print $e;
        }
    }

}